package cn.edu.xmu.oomall.customer.controller;


import cn.edu.xmu.javaee.core.aop.Audit;
import cn.edu.xmu.javaee.core.aop.LoginUser;
import cn.edu.xmu.javaee.core.exception.BusinessException;
import cn.edu.xmu.javaee.core.model.ReturnNo;
import cn.edu.xmu.javaee.core.model.ReturnObject;
import cn.edu.xmu.javaee.core.model.dto.UserDto;
import cn.edu.xmu.javaee.core.util.CloneFactory;
import cn.edu.xmu.oomall.customer.controller.dto.CustomerDto;
import cn.edu.xmu.oomall.customer.controller.dto.InfoDto;
import cn.edu.xmu.oomall.customer.controller.vo.CustomerVo;
import cn.edu.xmu.oomall.customer.dao.bo.Customer;
import cn.edu.xmu.oomall.customer.service.CustomerService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

@RestController /*Restful的Controller对象*/
@RequestMapping(value = "/customer", produces = "application/json;charset=UTF-8")
@RequiredArgsConstructor
@Slf4j
public class CustomerController {

    private final static Logger logger = LoggerFactory.getLogger(CustomerController.class);
    private final CustomerService customerService;

    /**
     * 买家查看自己的信息
     *
     * @param user
     * @return
     */
    @GetMapping()
    @Audit(departName = "customer")
    public ReturnObject getCustomerById(@LoginUser UserDto user) {

        Customer customer = customerService.getCustomerById(user);
        return new ReturnObject(new CustomerVo(customer));
    }


    /**
     * 买家修改自己的信息
     *
     * @param user
     * @param dto
     * @return
     */
    @PutMapping()
    @Audit(departName = "customer")
    public ReturnObject updateCustomer(@LoginUser UserDto user,
                                       @RequestBody CustomerDto dto) {
        Customer customer = CloneFactory.copy(new Customer(), dto);
        customer.setId(1L);
        logger.debug("updateCustomer: region = {}", customer);
        this.customerService.updateCustomer(customer, user);
        return new ReturnObject(ReturnNo.OK);
    }

    /**
     * 修改密码
     * @param user
     * @param dto
     * @return
     */
    @PutMapping("/password")
    @Audit(departName = "customer")
    public ReturnObject updatePassword(@LoginUser UserDto user,
                                       @RequestBody InfoDto dto) {
        if (dto.getNewPassword().length() != 6) {
            throw new BusinessException(ReturnNo.CUSTOMER_PASSWORDSAME, String.format(ReturnNo.CUSTOMER_PASSWORDSAME.getMessage(), "密码"));
        }
        Customer customer = new Customer();
        customer.setPassword(dto.getNewPassword());
        customer.setId(1L);
        logger.debug("updateCustomer: region = {}", customer);
        this.customerService.updatePassword(customer, user);
        return new ReturnObject(ReturnNo.OK);
    }

}
